from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.utils.safestring import mark_safe
from .models import Folder, Note, ShareLink


@admin.register(Folder)
class FolderAdmin(admin.ModelAdmin):
    """
    文件夹管理界面
    """
    list_display = (
        'id', 'name', 'count', 'isDefault', 'isShared', 
        'created_by', 'createdAt', 'updatedAt'
    )
    list_filter = ('isDefault', 'isShared', 'createdAt')
    search_fields = ('name', 'created_by__username', 'created_by__email')
    readonly_fields = ('id', 'createdAt', 'updatedAt')
    ordering = ('-id',)
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'count', 'parentId')
        }),
        ('状态设置', {
            'fields': ('isDefault', 'isShared')
        }),
        ('共享设置', {
            'fields': ('shareLink', 'sharePassword'),
            'classes': ('collapse',)
        }),
        ('系统信息', {
            'fields': ('id', 'created_by', 'createdAt', 'updatedAt', 'syncStatus', 'serverId'),
            'classes': ('collapse',)
        })
    )
    
    def get_queryset(self, request):
        """优化查询性能"""
        return super().get_queryset(request).select_related('created_by')


@admin.register(Note)
class NoteAdmin(admin.ModelAdmin):
    """
    笔记管理界面
    """
    list_display = (
        'id', 'title_short', 'folder_name', 'author', 
        'word_count', 'isShared', 'createdAt', 'updatedAt'
    )
    list_filter = ('isShared', 'syncStatus', 'createdAt', 'folderId')
    search_fields = ('title', 'content', 'author__username', 'author__email')
    readonly_fields = ('id', 'createdAt', 'updatedAt', 'word_count_display')
    ordering = ('-id',)
    
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'content', 'folderId', 'author')
        }),
        ('标签和分类', {
            'fields': ('tags',)
        }),
        ('共享设置', {
            'fields': ('isShared', 'shareLink', 'sharePassword'),
            'classes': ('collapse',)
        }),
        ('系统信息', {
            'fields': ('id', 'createdAt', 'updatedAt', 'syncStatus', 'serverId', 'word_count_display'),
            'classes': ('collapse',)
        })
    )
    
    def title_short(self, obj):
        """显示简短标题"""
        if len(obj.title) > 30:
            return obj.title[:30] + '...'
        return obj.title
    title_short.short_description = '标题'
    
    def folder_name(self, obj):
        """显示文件夹名称"""
        if obj.folderId:
            try:
                folder = Folder.objects.get(id=obj.folderId)
                return folder.name
            except Folder.DoesNotExist:
                return f'文件夹ID:{obj.folderId}(不存在)'
        return '未分类'
    folder_name.short_description = '文件夹'
    
    def word_count(self, obj):
        """显示字数"""
        return len(obj.content)
    word_count.short_description = '字数'
    
    def word_count_display(self, obj):
        """显示详细字数信息"""
        content_length = len(obj.content)
        title_length = len(obj.title)
        return f'标题: {title_length}字, 内容: {content_length}字, 总计: {title_length + content_length}字'
    word_count_display.short_description = '字数统计'
    
    def get_queryset(self, request):
        """优化查询性能"""
        return super().get_queryset(request).select_related('author')


@admin.register(ShareLink)
class ShareLinkAdmin(admin.ModelAdmin):
    """
    共享链接管理界面
    """
    list_display = (
        'shareId', 'resourceType', 'resourceId', 'shareLink', 
        'created_by', 'accessCount', 'expiresAt', 'createdAt'
    )
    list_filter = ('resourceType', 'createdAt', 'expiresAt')
    search_fields = ('shareId', 'shareLink', 'created_by__username', 'created_by__email')
    readonly_fields = ('shareId', 'createdAt', 'accessCount')
    ordering = ('-createdAt',)
    
    fieldsets = (
        ('基本信息', {
            'fields': ('shareId', 'shareLink', 'resourceType', 'resourceId')
        }),
        ('访问控制', {
            'fields': ('password', 'expiresAt')
        }),
        ('统计信息', {
            'fields': ('accessCount', 'created_by', 'createdAt'),
            'classes': ('collapse',)
        })
    )
    
    def get_queryset(self, request):
        """优化查询性能"""
        return super().get_queryset(request).select_related('created_by')
